const util = require('util');
const debug = util.debuglog('oil-game:login:dao');
const moment = require('moment');

const User = require('./userSchema');
const Level = require('../../../domain/level');
const WechatMpUser = require('./wechatMapUserSchema');
const Withdraw = require('../../../domain/withdraw');
const {
    Msg
} = require("../lib/consts")

//从Mogo中查询用户信息
exports.getUserByMongo = function (uid) {
    return new Promise((resolve, reject) => {
        User.findOne({uid}, function (err, user) {
            if (err) return reject(err);
            resolve(user && user.toObject());
        });
    });
}

/**
 * 通过uid 获取父用户的信息
 * @param uid
 * @returns {Promise<unknown>}
 */
exports.getParentByUid = function (uid) {
    return new Promise((resolve, reject) => {
        User.findOne({'uid': uid}, function (err, user) {
            if (err) return reject(err);
            resolve(user && user.toObject());
        });
    });
}

// 查询父用户信息
exports.searchParentInfo = function (unionid) {
    return new Promise((resolve, reject) => {
        WechatMpUser.findOne({unionid}, function (err, data) {
            if (err) return reject(err);
            resolve(data && data.toObject());
        });
    });
}

//根据手机号获取用户
exports.getUserByPhone = function (phone) {
    return new Promise((resolve, reject) => {
        User.findOne({phone}, function (err, data) {
            if (err) return reject(err);
            resolve(data && data.toObject());
        });
    });
}

//初始化保存用户数据
exports.saveNewUser = function (newUser) {
    return new Promise((resolve, reject) => {
        new User(newUser).save(function (err, userData) {
            if (err) return reject(err);
            resolve(userData);
        });
    });
}

//初始化保存用户附加信息
exports.saveUserByMySQL = function (uid) {
    return new Promise((resolve, reject) => {
        let mysqlClient = this.app.get('mysqlClient');//获取全局mysql client

        let sql = "SELECT COUNT(*) as count from user_info WHERE uid = ?";
        let args = [uid];
        mysqlClient.query(sql, args, function (err, res) {
            if (err) return reject(err);
            let objRes = JSON.parse(JSON.stringify(res));
            //存在相同uid的数据
            if (objRes[0].count !== 0) return resolve(res);

            //插入新数据
            sql = "INSERT INTO user_info (uid, money, oil, gmt_create, gmt_modified) VALUES(?, ?, ?, ?, ?)";
            let current = new Date().getTime();
            args = [uid, 0, 0, current, current];

            mysqlClient.query(sql, args, function (err, res) {//执行sql语句 函数insert和query等效
                if (err) return reject(err);
                resolve(res)
            });
        });
    });
}

//获取用户余额和石油
exports.getUserMoneyAndOil = function (uid) {
    debug("uid = %s  获取用户余额和石油", uid);
    return new Promise((resolve, reject) => {
        let mysqlClient = this.app.get('mysqlClient');//获取全局mysql client

        let sql = "SELECT money, total_money, oil, total_oil, essence_oil, total_essence_oil from user_info WHERE uid = ?";
        mysqlClient.query(sql, [uid], function (err, res) {
            if (err) {
                debug("uid = %s  获取用户余额和石油异常  %s", uid, JSON.stringify(err));
                return reject(err);
            }
            debug("uid = %s  获取用户余额和石油成功  %s", uid, JSON.stringify(res));
            let objRes = JSON.parse(JSON.stringify(res));
            resolve(objRes[0] || {});
        });
    });
}

//获取累积提现金额
exports.getTotalWithdrawByUid = function (uid) {
    console.log('uid')
    console.log(uid)
    return new Promise((resolve, reject) => {
        Withdraw.aggregate([
            {
                $match: {'uid': uid}
            },
            {
                $group: {
                    _id: null,
                    num_tutorial: {$sum: "$money"}
                }
            }], function (err, total) {
            if (err) {
                return reject(err);
            }
            if (total.length > 0) {
                resolve(total[0].num_tutorial);
            } else {
                resolve(0);
            }
        });
    });
}

exports.getTotalOil = function () {
    return new Promise((resolve, reject) => {
        let mysqlClient = this.app.get('mysqlClient');//获取全局mysql client

        let sql = "SELECT SUM(oil) as sum_oil from user_info WHERE id <> ?";
        mysqlClient.query(sql, [0], function (err, res) {
            if (err) return reject(err);
            let objRes = JSON.parse(JSON.stringify(res));
            resolve(objRes[0]);
        });
    });
}

//查询徒弟信息
exports.sonList = function (uid, pageNum) {
    return new Promise((resolve, reject) => {
        User.find({parent_id: uid}, {
            uid: 1,
            nickname: 1,
            parent_id: 1,
            video_num: 1,
            phone: 1,
            avatar: 1,
            gmt_create: 1
        }, function (err, users) {
            if (err) return reject(err);
            let list = [];
            for (let i = 0; i < users.length; i++) {
                list.push(
                    {
                        uid: users[i].uid,
                        nickname: users[i].nickname,
                        parent_id: users[i].parent_id,
                        video_num: users[i].video_num,
                        phone: users[i].phone,
                        avatar: users[i].avatar,
                        gmt_create: moment(users[i].gmt_create).format('YYYY-MM-DD HH:mm'),
                    }
                );
            }
            resolve(list);
        }).sort({gmt_create: -1}).skip((pageNum - 1) * 10).limit(10);
    });
}

/**
 * 查询徒孙信息
 * @param uid
 * @param pageNum
 * @returns {Promise<unknown>}
 */
exports.grandSonList = function (uid, pageNum) {
    return new Promise((resolve, reject) => {
        User.aggregate([{$match: {parent_id: uid}}, {
            $lookup: {
                from: "users",
                localField: "uid",
                foreignField: "parent_id",
                as: "child",
            }
        }, {
            $unwind: '$child'
        }, {
            $project: {
                '_id': 0,
                'uid': "$child.uid",
                'parent_id': "$child.parent_id",
                'nickname': "$child.nickname",
                'create_time': "$child.create_time",
                'avatar': "$child.avatar",
                'video_num': '$child.video_num',
                'phone': '$child.phone'
            }
        }
        ], function (err, users) {
            if (err) return reject(err);
            let list = [];
            for (let i = 0; i < users.length; i++) {
                list.push(
                    {
                        uid: users[i].uid,
                        nickname: users[i].nickname,
                        parent_id: users[i].parent_id,
                        video_num: users[i].video_num,
                        phone: users[i].phone,
                        avatar: users[i].avatar,
                        gmt_create: moment(users[i].gmt_create).format('YYYY-MM-DD HH:mm'),
                    }
                );
            }
            resolve(list);
        }).sort({gmt_create: -1}).skip((pageNum - 1) * 10).limit(10);
    });
}

/**
 * 增加徒弟石油贡献
 * @param uid
 * @returns {Promise<unknown>}
 */
exports.addApprenticeOil = function (uid, oil) {
    return new Promise((resolve, reject) => {
        User.updateOne({uid: uid}, {
            '$inc': {'apprentice_oil': oil, 'apprentice_oil_today': oil}
        }, function (err, data) {
            if (err) return reject(err);
            resolve();
        });
    });
}

/**
 * 增加徒孙石油贡献
 * @param uid
 * @param oil
 * @returns {Promise<unknown>}
 */
exports.addDiscipleOil = function (uid, oil) {
    return new Promise((resolve, reject) => {
        User.updateOne({uid: uid}, {
            '$inc': {'disciple_oil': oil, 'disciple_oil_today': oil}
        }, function (err, data) {
            if (err) return reject(err);
            resolve();
        });
    });
}

//获取用户等级限制
exports.getUserGradeLimit = function (uid) {
    debug("uid = %s 获取用户等级限制", uid);
    let mysqlClient = this.app.get('mysqlClient');
    let sql = `select apprentice,grandson,name,trade_fee,cancel_fee from _levels;`
    return new Promise((resolve, reject) => {
        mysqlClient.query(sql, [], function (err, data) {
            if (err) {
                debug('获取用户等级限制异常 %s', JSON.stringify(err));
                return reject(err);
            }
            debug('获取用户等级限制异常 %s', JSON.stringify(data));
            let objRes = JSON.parse(JSON.stringify(data));
            if (!(Array.isArray(objRes) && objRes.length > 0))
                return reject(new Error(Msg.NOT_USER_GRADE_LIMIT));

            return resolve(objRes);
        });
    });
}

//获取用户矿层信息
exports.getUserLevelInfo = function (uid) {
    return new Promise((resolve, reject) => {
        Level.find({uid: uid}, function (err, data) {
            if (err) {
                return reject(err);
            }
            resolve(data);
        }).sort({'level_num': 1});
    });
}


